package xyz.ibenben.zhongdian.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;
import xyz.ibenben.zhongdian.common.util.HttpServletResponseUtil;
import xyz.ibenben.zhongdian.system.entity.ChinaCity;
import xyz.ibenben.zhongdian.system.entity.ChinaRegion;
import xyz.ibenben.zhongdian.system.entity.HouseInfo;
import xyz.ibenben.zhongdian.system.entity.ajax.AjaxJson;
import xyz.ibenben.zhongdian.system.entity.enums.HouseTypeEnum;
import xyz.ibenben.zhongdian.system.form.HouseInfoForm;
import xyz.ibenben.zhongdian.system.service.HouseInfoService;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 房屋信息控制类
 * 提供了一些基本的服务，如初始化、获取房屋信息列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Slf4j
@Controller
@SessionAttributes("houseInfoForm")
@RequestMapping("/houseInfo")
@SuppressWarnings(value="unchecked")
public class HouseInfoController extends BaseController{
	/* 实体名称 */
	private static final String ENTITYNAME = "houseInfo";

	private final HouseInfoService houseInfoService;
	private final RedisService redisService;

	@Autowired
	public HouseInfoController(HouseInfoService houseInfoService, RedisService redisService) {
		this.houseInfoService = houseInfoService;
		this.redisService = redisService;
	}

	/**
	 * 初始化
	 * @param map 参数
	 * @param houseInfoForm 条件参数
	 */
	@ModelAttribute
	public void init(Model map, @ModelAttribute HouseInfoForm houseInfoForm){
		map.addAttribute("provinceList", redisService.get("provinceList"));
		map.addAttribute("cityList", redisService.get("cityList"));
		map.addAttribute("regionList", redisService.get("regionList"));
		HouseInfoForm newHouseInfoForm = new HouseInfoForm();
		if(houseInfoForm != null){
			newHouseInfoForm = houseInfoForm;
		}
		map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newHouseInfoForm);
	}

	/**
	 * 获取房屋信息列表
	 * @param map 参数
	 * @param houseInfoForm 条件参数
	 * @return 页面
	 */
	@RequestMapping(value="/getall")
	@SystemControllerLog(description = "获取房屋信息列表")
	public String getall(Model map, @ModelAttribute HouseInfoForm houseInfoForm){
		log.info("getall param HouseInfoForm: {}", houseInfoForm.toString());
		map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), houseInfoForm);
		Page<HouseInfo> page = PageHelper.startPage(houseInfoForm.getPageIndex(), houseInfoForm.getPageSize());
		List<HouseInfo> list = houseInfoService.selectByExample(houseInfoForm.buildSearchCommond());
		if(list != null && !list.isEmpty()){
			for(HouseInfo info: list){
				info.setProvinceName(redisService.get(info.getProvince()).toString());
				info.setCityName(redisService.get(info.getCity()).toString());
				info.setRegionName(redisService.get(info.getRegion()).toString());
			}
		}
		map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
		map.addAttribute(Constants.PI, page.toPageInfo());
		return String.format(Constants.LISTPAGE, ENTITYNAME);
	}

	/**
	 * 删除房屋信息记录
	 * @param id 主键
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value = "/{id}/delete")
	@SystemControllerLog(description = "删除房屋信息记录")
	public String delete(@PathVariable Long id, HttpServletRequest request) {
		houseInfoService.delete(id, request);
		return String.format(Constants.REDIRECT, ENTITYNAME);
	}

	/**
	 * 删除房屋信息列表
	 * @param houseInfoForm 条件参数
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping("/deleteall")
	@SystemControllerLog(description = "删除房屋信息列表")
	public String deleteall(@ModelAttribute HouseInfoForm houseInfoForm,
			HttpServletRequest request) {
		if(houseInfoForm.getSelectIds() != null){
			String[] ids = houseInfoForm.getSelectIds().split(Constants.COMMA);
			for(String id: ids){
				houseInfoService.delete(Long.parseLong(id), request);
			}
		}
		return String.format(Constants.REDIRECT, ENTITYNAME);
	}

	/**
	 * 打开房屋信息添加页面
	 * @param map 参数
	 * @return 页面
	 */
	@RequestMapping(value="/add", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开房屋信息添加页面")
	public String openAddPage(Model map){
		map.addAttribute(ENTITYNAME, new HouseInfo());
		return String.format(Constants.ADDPAGE, ENTITYNAME);
	}

	/**
	 * 保存房屋信息添加记录
	 * @param t 实体
	 * @param bindingResult 校验
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value="/add", method= RequestMethod.POST)
	@SystemControllerLog(description = "保存房屋信息添加记录")
	public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) HouseInfo t,
			BindingResult bindingResult, HttpServletRequest request){
		if(StringUtils.isNotBlank(t.getHouseName())){
			List<HouseInfo> list = houseInfoService.findByHouseName(t.getHouseName());
			if(null != list && !list.isEmpty()){
				bindingResult.rejectValue("houseName", "misFormat", "这个房屋名称已经存在了！请更改!");
				return String.format(Constants.ADDPAGE, ENTITYNAME);
			}
		}
		if (!bindingResult.hasErrors()) {
			t.setType(HouseTypeEnum.PRIVATE);
			houseInfoService.save(t, request);
			return String.format(Constants.REDIRECT, ENTITYNAME);
		} else {
			return String.format(Constants.ADDPAGE, ENTITYNAME);
		}
	}

	/**
	 * 打开房屋信息修改页面
	 * @param map 参数
	 * @param id 主键
	 * @return 页面
	 */
	@RequestMapping(value="/{id}/edit", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开房屋信息修改页面")
	public String openEditPage(Model map, @PathVariable Long id){
		map.addAttribute(ENTITYNAME, houseInfoService.findOneWithImage(id));
		return String.format(Constants.EDITPAGE, ENTITYNAME);
	}

	/**
	 * 更新房屋信息修改记录
	 * @param t 实体
	 * @param bindingResult 校验
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value="/edit", method= RequestMethod.POST)
	@SystemControllerLog(description = "更新房屋信息修改记录")
	public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) HouseInfo t,
			BindingResult bindingResult, HttpServletRequest request){
		HouseInfo info = houseInfoService.selectByKey(t.getId());
		if(!info.getHouseName().equals(t.getHouseName())){
			List<HouseInfo> list = houseInfoService.findByHouseName(t.getHouseName());
			if(null != list && !list.isEmpty()){
				bindingResult.rejectValue("houseName", "misFormat", "这个房屋名称已经存在了！请更改!");
				return String.format(Constants.EDITPAGE, ENTITYNAME);
			}
		}
		if (!bindingResult.hasErrors()) {
			houseInfoService.updateNotNull(t, request);
			return String.format(Constants.REDIRECT, ENTITYNAME);
		} else {
			return String.format(Constants.EDITPAGE, ENTITYNAME);
		}
	}

	/**
	 * 浏览房屋信息记录
	 * @param map 参数
	 * @param id 主键
	 * @param houseInfoForm 条件参数
	 * @return 页面
	 */
	@RequestMapping(value="/{id}/view", method= RequestMethod.GET)
	@SystemControllerLog(description = "浏览房屋信息记录")
	public String openViewPage(Model map, @PathVariable Long id,
			@ModelAttribute HouseInfoForm houseInfoForm){
		HouseInfo info = houseInfoService.findOneWithImage(id);
		info.setProvinceName(redisService.get(info.getProvince()).toString());
		info.setCityName(redisService.get(info.getCity()).toString());
		info.setRegionName(redisService.get(info.getRegion()).toString());
		map.addAttribute(ENTITYNAME, info);
		return String.format(Constants.VIEWPAGE, ENTITYNAME);
	}

	/**
	 * 打开房屋信息导入页面
	 * @return 页面
	 */
	@RequestMapping(value="/import", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开房屋信息导入页面")
	public String openImportPage(){
		return "houseInfo/import";
	}

	/**
	 * 提交房屋信息导入文件
	 * @param map 参数
	 * @param file 参数
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value="/import", method= RequestMethod.POST)
	@SystemControllerLog(description = "提交房屋信息导入文件")
	public String postUploadFile(Model map, @RequestParam MultipartFile file, HttpServletRequest request){
		if(file != null){
			try {
				houseInfoService.importData(file.getBytes(), request);
			} catch (Exception e) {
				throw new MyException(ExceptionEnum.CONVERTFILEEXCEPTION, e);
			}
			return String.format(Constants.REDIRECT, ENTITYNAME);
		}else{
			return HttpServletResponseUtil.processModelAndView(map, "最多可以上传6张图片", "houseInfo/import");
		}
	}

	/**
	 * 导出房屋信息记录
	 * @param houseInfoForm 条件参数
	 * @param request 请求
	 * @param response 参数
	 */
	@RequestMapping(value="/export", method= RequestMethod.GET)
	@SystemControllerLog(description = "导出房屋信息记录")
	public void openExportPage(@ModelAttribute HouseInfoForm houseInfoForm,
			HttpServletRequest request, HttpServletResponse response){
		List<Long> list = new ArrayList<>();
		if(houseInfoForm.getSelectIds() != null){
			String[] ids = houseInfoForm.getSelectIds().split(Constants.COMMA);
			for(String id: ids){
				list.add(Long.parseLong(id));
			}
		}
		houseInfoService.export(list, request, response);
	}

	/**
	 * 获取城市信息列表
	 * @param provinceCode 参数
	 * @return 页面
	 */
	@RequestMapping("/getCityList")
	@ResponseBody
	@SystemControllerLog(description = "获取城市信息列表")
	public String getCityList(String provinceCode){
		List<ChinaCity> list = (List<ChinaCity>) redisService.get("city" + provinceCode);
		return JSONArray.fromObject(list).toString();
	}

	/**
	 * 获取市区信息列表
	 * @param cityCode 参数
	 * @return 页面
	 */
	@RequestMapping("/getRegionList")
	@ResponseBody
	@SystemControllerLog(description = "获取市区信息列表")
	public String getRegionList(String cityCode){
		List<ChinaRegion> list = (List<ChinaRegion>) redisService.get("region" + cityCode);
		return JSONArray.fromObject(list).toString();
	}

	/**
	 * 获取所有房屋信息列表
	 * @param response 参数
	 * @return 页面
	 */
	@RequestMapping("/getAllHouse")
	@ResponseBody
	@SystemControllerLog(description = "获取所有房屋信息列表")
	public String getAllHouse(HttpServletResponse response){
		AjaxJson aj = houseInfoService.getHouseInfoList();
		HttpServletResponseUtil.responseWriter(response, aj);
		return null;
	}
	
}

